package engine;

import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

public class NoobEngine implements Runnable 
{
	final double ns = 1000000000.0 / 60.0;
	private static final int FPS = 60;
	private int width, height;
	private String title;
	private static boolean isRunning = false,isFullscreen;
	private static Thread thread;
	
	
	public NoobEngine(int width, int height, String title, boolean fullscreen)
	{
		this.width = width;
		this.height = height;
		this.title = title;
		this.isFullscreen = fullscreen;
		start();
	}
	
	private void initGL() 
	{
		System.out.println("intit");
		glShadeModel(GL_SMOOTH);                                                  
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);	
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, width, height, 0, 1, -1);
		glMatrixMode(GL_MODELVIEW);
		glEnable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		//Display.setVSyncEnabled(VSync);//Setup VSync
	}
	
	public synchronized void start()
	{
		isRunning = true;
		thread = new Thread(this, title);
		thread.start();
	}
	
	public synchronized void stop()
	{
		isRunning = false;
		try
		{
			thread.join();
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
	}
 
	
	
	@Override
	public void run() 
	{
		//Initialize OGL
		try {
			
			Display.create();
			Display.setDisplayMode(new DisplayMode(width, height));
			Display.setTitle(title);
			Display.setFullscreen(isFullscreen);
			initGL();
		} catch (LWJGLException e) {
			e.printStackTrace();
			System.exit(0);
		}
		glClearColor(0.0f, 0.0f, 0.0f, 0);
		
		long now, lastTime = System.nanoTime(), timer = System.currentTimeMillis();//time at last frame, last fps time
		double delta;
		int fps=0;
		
		while(isRunning)//!Display.isCloseRequested())
		{
			if(Display.isCloseRequested())
			{
				isRunning=false;
				Display.destroy();
				return;
			}
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);//Clear screen
			now = System.nanoTime();
			delta = (now - lastTime) / ns;
			lastTime = now;
			
			glColor3f(1, 1, 1);//Drop color to default white(correct texture rendering)
			
			//render here --->
			//	renderServerSelect();
			//	updateServerSelect(delta);
			//<--- end of rendering
			++fps;
			
			if(System.currentTimeMillis() - timer > 1000)
			{
				timer += 1000;
				Display.setTitle(title + " fps "+fps);
				fps=0;
			}
				
			Display.update();
			Display.sync(FPS);
		}
	}
	
	public boolean isRunning()
	{
		return isRunning;
	}
	
	
}
